package com.smart.community.common.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSSException;
import com.smart.community.common.base.ex.BaseException;
import com.smart.community.common.base.result.ResultStatus;
import com.smart.community.common.oss.config.OssConfigProperties;
import com.smart.community.common.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 子未语
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    public static final String OSS_IMAGE_PREFIX = "images/";

    @Resource
    private OSS oss;
    @Resource
    private OssConfigProperties ossConfigProperties;


    @Override
    public String upload(MultipartFile multipartFile) {
        // 获取到上传文件的后缀
        String oldName = multipartFile.getOriginalFilename();
        // 获取到当前的系统时间
        DateTime date = DateUtil.date();
        // 获取上传文件的后缀名
        String substring = oldName.substring(oldName.lastIndexOf("."));
        // 将工具类生成的所有数据进行拼接，成为上传到系统中的文件名
        String key = String.format("%s%s/%s%s", OSS_IMAGE_PREFIX, getPath(date), getNewName(date), substring);
        try {
            // 获取上传文件的Stream流
            InputStream inputStream = multipartFile.getInputStream();
            // BucketName 是协议后面的那一部分，   key是新文件的名字  inputStream是二进制流
            oss.putObject(ossConfigProperties.getBucketName(), key, inputStream);
        } catch (OSSException | ClientException | IOException e) {
            throw new RuntimeException(e);
        }
        return ossConfigProperties.getDoMain() + key;
    }

    private String getPath(DateTime date) {
        // 将时间进行格式化获取到上传的目录
        return DateUtil.format(date, DatePattern.NORM_DATE_PATTERN);
    }
    private String getNewName(DateTime date) {
        // 将时间进行格式化获取到整个时间信息
        String fileName = DateUtil.format(date, DatePattern.PURE_DATETIME_PATTERN);
        // 生成四位数的随机数
        String s = RandomUtil.randomNumbers(4);
        return String.format("%s%s", fileName, s);
    }

}
